﻿using Batman.Cms.Core.Const;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Batman.Cms.Core.Providers
{
    public class ProfileService : IProfileService
    {
        private UserManager<IdentityUser> _userManager;

        public ProfileService(UserManager<IdentityUser> userManager)
        {
            _userManager = userManager;
        }

        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            try
            {
                var claims = new List<Claim>();

                var userId = context.Subject.GetSubjectId();
                if (userId != null)
                {
                    var user = await _userManager.FindByIdAsync(userId);
                    if (user != null)
                    {
                        // 显示用户名
                        claims.Add(new Claim(BatmanCliamTypes.DisplayName, user.UserName));
                    }
                }

                context.IssuedClaims.AddRange(claims);
            }
            catch (Exception)
            {
                //log your error
            }
        }

        public Task IsActiveAsync(IsActiveContext context)
        {
            context.IsActive = true;
            return Task.FromResult(0);
        }
    }
}
